<template>
    <el-select
        v-model="data"
        filterable
        remote
        clearable
        reserve-keyword
        :remote-method="remoteMethod"
        :loading="selectLoading"
        loading-text="正在加载中..."
        :popper-append-to-body="false"
        :teleported="false"
        placeholder="请输入"
        class="form-input select"
        :value-key="basicInfo.key"
        @change="onChange"
        @clear="onClear"
    >
        <template #prefix>
            <span class="label" v-if="label">
                <span>{{ label }}</span>
            </span>
            <slot name="icon"></slot>
        </template>
        <el-option
            v-for="item in list"
            :key="item[basicInfo.value]"
            :label="item[basicInfo.label]"
            :value="!basicInfo.key ? item[basicInfo.value] : item"
        />
    </el-select>
</template>

<script lang="ts" setup>
import { ref, defineProps, defineEmits, defineExpose, watchEffect } from 'vue';
import { getCompanyInfo } from '@/api/delivery/creativeManage';

const emit = defineEmits(['onChange']);

const list: any = ref([]);

const props = defineProps({
    label: {
        type: String,
        default: '',
    },
    basicInfo: {
        type: Object,
        default: () => {
            return {
                value: 'customerId',
                label: 'company',
                key: '',
            };
        },
    },
    queryType: {
        type: String,
        default: '1',
    },
    targetData: {
        type: String,
        default: '',
    },
});

const selectLoading = ref(false);
const data = ref('');

const remoteMethod = async (query: string) => {
    if (query) {
        selectLoading.value = true;
        try {
            const data = await getCompanyInfo(query);
            list.value = data;
        } finally {
            selectLoading.value = false;
        }
    }
};

const onChange = (val: string) => {
    emit('onChange', val);
    list.value = [];
};

const onClear = () => {
    data.value = '';
    list.value = [];
    emit('onChange', '');
};

watchEffect(() => {
    if (props.targetData) {
        data.value = props.targetData;
    }
});

// 对外暴露可执行方法
defineExpose({
    onClear,
});
</script>

<style lang="scss" scoped></style>
